<template>
  <div v-loading="pageLoading" class="user-add-page">
    <div v-if="operationFlag==='edit'" class="children-page-title">
      <div class="page-path">
        <span>首页 > 个人中心</span>
      </div>
      <div class="control-button">
        <el-button size="mini" @click="cancelUsersSubmit">取 消</el-button>
        <el-button size="mini" type="primary" @click="addUsersSubmit">保 存</el-button>
      </div>
    </div>
    <div class="content" :class="operationFlag==='edit'?'isEdit':''">
      <el-scrollbar class="page-scrollbar">
        <!-- 用户信息 -->
        <div class="user-info-box">
          <div class="title-box"><span class="border" /><span>我的信息</span></div>
          <div class="content-box">
            <el-form ref="userAddForm" :model="userInfoForm" :rules="formRules" label-width="80px" size="mini">
              <el-form-item label="个人头像:" class="avatar-wrapper">
                <el-upload
                  ref="uploadSubmit"
                  action="/ucenter/api/v2/file/upload"
                  :headers="uploadHeader"
                  :show-file-list="false"
                  :data="subForm"
                  :auto-upload="false"
                  accept=".jpg,.jpeg,.png"
                  :on-change="avatarChoosed"
                  :on-error="avatarUploadError"
                  :on-success="avatarUploadSuccess"
                >
                  <div class="user-avatar-box">
                    <img :src="userAvatar || errorPhoto" class="user-avatar" :onerror="`this.src='${errorPhoto}'`">
                    <div class="user-avatar-text">上传</div>
                  </div>
                </el-upload>
              </el-form-item>
              <el-form-item label="账号:">
                <span class="only-read-text">{{ userInfoForm.account }}</span>
              </el-form-item>
              <el-form-item label="姓名:">
                <span class="only-read-text">{{ userInfoForm.userName }}</span>
              </el-form-item>
              <el-form-item label="用户编号:">
                <span class="only-read-text">{{ userInfoForm.staffCode }}</span>
              </el-form-item>
              <el-form-item label="性别:">
                <span class="only-read-text">{{ userInfoForm.gender === 1 ? '男' : '女' }}</span>
              </el-form-item>
              <el-form-item label="邮箱:" prop="email">
                <template v-if="operationFlag!=='read'">
                  <el-input v-model.trim="userInfoForm.email" maxlength="45" placeholder="请输入您的邮箱" />
                </template>
                <span v-if="operationFlag==='read'" class="only-read-text">{{ userInfoForm.email }}</span>
                <span v-if="operationFlag==='read'" class="only-read-text" @click="handleEdit"><svg-icon icon-class="bianjitianxie-solid" /></span>
              </el-form-item>
              <el-form-item label="电话:" prop="phone">
                <template v-if="operationFlag!=='read'">
                  <el-input v-model.trim="userInfoForm.phone" maxlength="11" placeholder="请输入您的电话" />
                </template>
                <span v-if="operationFlag==='read'" class="only-read-text">{{ userInfoForm.phone }}</span>
                <span v-if="operationFlag==='read'" class="only-read-text" @click="handleEdit"><svg-icon icon-class="bianjitianxie-solid" /></span>
              </el-form-item>
              <el-form-item label="密码设置:">
                <template v-if="operationFlag!=='read'">
                  <el-input v-model.trim="userInfoForm.password" maxlength="20" show-word-limit placeholder="请设置新密码" />
                </template>
                <span v-if="operationFlag==='read'" class="only-read-text">***********</span>
                <span v-if="operationFlag==='read'" class="only-read-text" @click="handleEdit"><svg-icon icon-class="bianjitianxie-solid" /></span>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- <my-position :user-id="userEditId" />

        <my-tabs :user-id="userEditId" /> -->
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { queryUserDetail, saveUserInfo } from '@/api/users'
import { getDictByType } from '@/api/dataDict'
import { getToken } from '@/utils/auth'
/* import MyPosition from './component/AuthPosition'
import MyTabs from './MyTabs' */
export default {
  name: 'UserSetting',
  components: {
    /* MyPosition,
    MyTabs */
  },
  data() {
    const validateEmail = (rule, value, callback) => {
      if (value && value.length > 0) {
        // var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
        var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
        if (!reg.test(value)) {
          return callback(new Error('请输入正确的邮箱地址'))
        }
      }
      callback()
    }
    /* const validatePhone = (rule, value, callback) => {
      if (!value || value.length === 0) {
        return callback(new Error('请输入手机号码'))
      } else {
        if (!(/^1[3456789]\d{9}$/.test(value))) {
          return callback(new Error('请输入正确的手机号码'))
        }
      }
      callback()
    } */

    return {
      isChooseHead: false,
      pageLoading: false,
      operationFlag: 'read',
      uploadHeader: {},
      userAvatar: '',
      errorPhoto: require('@/assets/login_images/user-avatar.png'),
      userEditId: '',
      orgFullPath: '',
      userOrgName: '',
      userTypeLabel: '',
      subForm: {},
      userInfoForm: {
        userId: '',
        userPhoto: '',
        userName: '',
        orgId: '',
        type: '',
        account: '',
        staffCode: '',
        gender: '',
        email: '',
        phone: '',
        state: 1,
        password: '',
        role: [],
        userGroup: [],
        userPost: []
      },
      formRules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          // { validator: validatePhone, trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ]
      },
      accountType: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  async created() {
    // 配置上传header
    this.uploadHeader = { token: getToken(), Authorization: `Bearer ${getToken()}` }
    // 获取头像
    this.userAvatar = this.user.photo
    this.userEditId = this.user.userId
    this.userInfoForm.orgId = this.user.orgId || ''
    this.userOrgName = this.user.orgName || ''
    this.orgFullPath = this.user.orgFullName
    await this.getAccountType()
    this.getUserDetail()
  },
  mounted() {
  },
  methods: {
    async getAccountType() {
      const params = {
        domainCode: 'platform',
        appCode: 'ucenter',
        dictTypeCode: 'USER_TYPE_LIST'
      }
      await getDictByType(params).then(res => {
        this.accountType = res.data || []
      })
    },
    // 获取当前用户详细数据
    getUserDetail() {
      queryUserDetail(this.userEditId).then(res => {
        if (res.success === 1) {
          this.userInfoForm.orgId = res.data.orgId
          this.userInfoForm.userId = res.data.userId
          this.userOrgName = res.data.orgName
          this.userInfoForm.type = res.data.type
          this.userInfoForm.account = res.data.account
          this.userInfoForm.userName = res.data.userName
          this.userInfoForm.staffCode = res.data.staffCode
          this.userInfoForm.gender = res.data.gender
          this.userInfoForm.email = res.data.email
          this.userInfoForm.phone = res.data.phone
          this.userInfoForm.state = res.data.state
          this.accountType.forEach(item => {
            if (Number(item.dictCode) === Number(res.data.type)) {
              this.userTypeLabel = item.dictName
            }
          })
          this.pageLoading = false
        }
      })
    },
    // 头像选择
    avatarChoosed(file, files) {
      const fileName = file.name
      const regex = /(.jpg|.jpeg|.png)$/
      if (regex.test(fileName.toLowerCase())) {
        this.userAvatar = URL.createObjectURL(file.raw)
        this.operationFlag = 'edit'
      } else {
        this.$message({
          message: '只支持jpg、jpeg、png格式',
          type: 'warning'
        })
      }
    },
    // 头像上传失败
    avatarUploadError() {
      this.$message.error('操作失败')
    },
    // 头像上传成功
    avatarUploadSuccess(res, file) {
      this.$message.success('操作成功')
      setTimeout(() => {
        this.user.photo = URL.createObjectURL(file.raw)
        this.userAvatar = this.user.photo
        this.$refs.uploadSubmit.clearFiles()
        this.operationFlag = 'read'
      }, 500)
    },
    // 点击编辑
    handleEdit() {
      this.operationFlag = 'edit'
    },
    // 取消用户添加
    cancelUsersSubmit() {
      this.$confirm('确认取消当前操作？取消将不保存当前操作', '取消保存', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.operationFlag = 'read'
        this.userInfoForm.email = this.user.email
        this.userInfoForm.phone = this.user.phone
        this.userInfoForm.password = ''
      }).catch(() => {
      })
    },
    // 提交用户添加
    addUsersSubmit() {
      this.subForm = {
        email: this.userInfoForm.email,
        phone: this.userInfoForm.phone,
        password: this.userInfoForm.password
      }
      this.$confirm('确认保存当前用户信息？', '用户设置', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.userAvatar === this.user.photo || this.userAvatar === '') {
          const newForm = new FormData()
          newForm.append('email', this.userInfoForm.email)
          newForm.append('phone', this.userInfoForm.phone)
          newForm.append('password', this.userInfoForm.password)
          saveUserInfo(newForm, this.userEditId).then(res => {
            if (res.success === 1) {
              this.$message.success('操作成功')
              this.operationFlag = 'read'
            }
          })
        } else {
          this.$refs.uploadSubmit.submit()
        }
      }).catch(() => {
      })
    }
  }
}

</script>
<style lang="scss" scoped>
  .user-add-page{
    background-color: #fff;

      /deep/ .table-list-header th{
        border-top: 0;
        background-color: #eee;
      }

      /deep/ .el-table th.is-leaf{
        border-bottom: 0;
      }

      /deep/ .el-table .cell{
        padding: 0 20px;
      }

    /deep/ .user-add-dialog{

      .el-dialog__body{
        padding: 0;

        .has-choosed-tags{

          .el-tag{
            margin-right: 5px;
            margin-bottom: 5px;
          }
        }
      }

      .dialog-flex{
        display: flex;

        .table-choose-boox{
          padding: 10px 15px 5px;
          width: 100%;
        }
      }

      .left-box{
        box-shadow: none;
        width: 230px;
        padding-bottom: 20px;
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;

        .page-scrollbar{
          height: 379px;
        }

        .left-choose-list-content{
          padding: 0;

          .left-list-item{
            position: relative;
            padding: 0 20px;
            height: 30px;
            line-height: 30px;
            cursor: pointer;

            .item-text{
              padding-right: 15px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            &:hover{
              background-color: $qup-color-hover;

              .add-icon{
                display: block;
              }
            }

            .add-icon{
              display: none;
              position: absolute;
              right: 20px;
              top: 2px;
              z-index: 2;

              .add{
                font-size: 16px;
                color: $qup-color-primary;
              }
            }
          }
        }
      }

      .rgiht-box{
        width: 720px;
        background-color: #f7f7f7;
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;

        .backgroud-slot{
          height: 100%;
          background-color: #fff;
          margin-left: 10px;
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }

        .title-info{
          padding: 20px 20px 10px 20px;
        }

        .footer-button{
          padding: 15px 20px;
          text-align: right;
        }
      }
    }

    .content{
      height: calc(100vh - 104px);
      &.isEdit{
        height: calc(100vh - 154px);
      }

      /deep/ .function-box{
        padding: 0 20px;
      }

      /deep/.table-list-box{
        margin: 0 20px;
        width: auto;
      }

      /deep/.button-box{
        display: flex;
        justify-content: space-between;
        padding: 20px;

        .title-box{
          padding: 0;
          line-height: 30px;
        }
      }

      /deep/.title-box{
        padding: 20px;
        color: $colorA;
        font-weight: 600;
        font-size: 14px;

        .border{
          display: inline-block;
          width: 2px;
          height: 18px;
          margin-right: 4px;
          background-color: $qup-color-primary;
          vertical-align: -4px;
        }
      }
      .content-box{

        .avatar-wrapper{
          /deep/ .el-form-item__content{
            line-height: 10px;
          }
        }

        .user-avatar-box{
          position: relative;
          width: 40px;
          height: 40px;
          margin-top: -5px;
          margin-left: 5px;
        }

        .user-avatar-text{
          position: absolute;
          top: 0;
          left: 0;
          width: 40px;
          height: 40px;
          line-height: 40px;
          font-size: 12px;
          border-radius: 50%;
          background-color: rgba(0,0,0,.25);
          color: #fff;
          text-align: center;
          cursor: pointer;
        }

        .user-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }

        .type-button{
          display: inline-block;
          width: 90px;
          height: 28px;
          line-height: 28px;
          text-align: center;
          border-radius: 4px;
          color: $colorA;
          border: 1px solid #DCDFE6;
          background-color: #fff;
          margin-right: 10px;
          font-size: 12px;
          cursor: pointer;
          transition: .2s;

          &.on{
            color: $qup-color-primary;
            border: 1px solid $qup-color-primary;
            transition: .2s;
          }
        }

        .el-form-item{
          // margin-bottom: 10px !important;
          /deep/ .el-form-item__label{
            color: $colorB;
          }

          .only-read-text{
            font-size: 12px;
            color: $colorA;
            margin-left: 10px;
            &.green{
              color: $qup-color-primary;
            }
            &.red{
              color: $qup-color-danger;
            }
            .svg-icon{
              cursor: pointer;
              color: #ccc;
              vertical-align: -3px;
            }
          }

          &.has-org-popup{
            position: relative;

            .org-popup-box{
              position: absolute;
              left: 0;
              top: 30px;
              z-index: 5;
            }
          }

          &:first-child{
            margin-bottom: 3px !important;
          }

          .org-path-info{
            font-size: 12px;
            color: $colorC;
            line-height: 12px;
            padding: 5px 0;
          }

          .choose-org-item{

            /deep/ .el-input__inner{
              cursor: pointer;
              padding-right: 25px !important;
            }

           /deep/ .svg-icon{
              margin-right: 5px !important;
              cursor: pointer;
            }
          }

          /deep/ .el-radio__label{
            font-size: 12px;
          }

         /deep/ .el-input{
            width: 200px;
          }
        }
      }
    }
  }
</style>

